package com.lu.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.lu.reggie.common.BaseContext;
import com.lu.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    //路径匹配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        log.info("拦截到请求：{}",url);
        String[] paths = new String[] {
                "/employee/login", "/employee/logout", "/backend/**", "/front/**", "/user/sendMsg", "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断该次访问的路径是否需要放行
        boolean flag = check(paths, url);
        if (flag) {
            log.info("本次登陆{}不需要拦截", url);
            filterChain.doFilter(request, response);
            return;
        }
        //网页登录
        if (!(null == request.getSession().getAttribute("employee"))) {
            log.info("用户已登录,ID为{}", request.getSession().getAttribute("employee"));
            //登陆后再将ID存入局部线程变量中
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        //移动端登录
        if (!(null == request.getSession().getAttribute("user"))) {
            log.info("用户已登录,ID为{}", request.getSession().getAttribute("user"));
            //登陆后再将ID存入局部线程变量中
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        log.info("请登录!");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    public boolean check(String[] paths, String url) {
        for (String path : paths) {
            boolean match = PATH_MATCHER.match(path, url);
            if (match) {
                return true;
            }
        }
        return false;
    }


}
